// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
const _ = db.command
// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const setting = await db.collection('Setting').doc('5a93cec95edf0fc400679b4f23f37a84').get()

  switch (event.op) {
    case 'updateGold':
      return updateGold();
      break;
    case 'checkOpenTimes':
      return checkOpenTimes();
      break;
    case 'updateOpenTimes':
      return updateOpenTimes();
      break;

  }

  async function updateGold() {

    await db.collection('User').where({
      _openid: wxContext.OPENID,
    }).update({
      data: {
        dialTimes: _.inc(1),
        gold: _.inc(event.awardGold),
        active: _.inc(1),
      }
    })
    //
    if (event.awardGold > 0) {
      await db.collection('Record').add({
        data: {
          createTime: db.serverDate(),
          content: {
            op: 'dial',
            awardGod: event.awardGold,
          },
          _openid: wxContext.OPENID,
        }
      })
    }
    return event.awardGold

  }
  async function checkOpenTimes() {
    let res = await db.collection('User').where({
      _openid: wxContext.OPENID
    }).field({
      dialTimes: true,
    }).get()
    let dialTimes = res.data[0].dialTimes
    if (dialTimes >= setting.data.maxDialTimes) {
      return 'notEnough'
    }
    return 'pass'
  }
  async function updateOpenTimes() {

    let res = await db.collection('User').where({
      _openid: wxContext.OPENID
    }).update({
      data: {
        gold: _.inc(-300),
        dialTimes: setting.data.maxDialTimes - setting.data.awardDialTimes
      }
    })
    return res
  }


}